package com.aiti.lulian.service.newCard;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.newCard.CardEnterpriseMaterialDto;
import com.aiti.lulian.entity.newCard.CardEnterpriseMaterial;
import com.aiti.lulian.mapper.newCard.CardEnterpriseMaterialMapper;
import com.aiti.lulian.service.CardEnterpriseMaterialService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class CardEnterpriseMaterialServiceImpl extends ServiceImpl<CardEnterpriseMaterialMapper, CardEnterpriseMaterial> implements CardEnterpriseMaterialService {

    @Autowired
    private CardEnterpriseMaterialMapper cardEnterpriseMaterialMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message addOrUpdateEnterpriseMaterial(CardEnterpriseMaterialDto dto) {
        CardEnterpriseMaterial enterpriseMaterial = new CardEnterpriseMaterial();
        BeanUtils.copyProperties(dto, enterpriseMaterial);
        if (StrUtil.isBlank(dto.getBaseId())) {
            // 新增物料
            enterpriseMaterial.setBaseId(IdUtil.simpleUUID());
            enterpriseMaterial.setCreatorCardId(dto.getCardId());
            enterpriseMaterial.setBaseCreateTime(new Date());
            enterpriseMaterial.setBaseUpdateTime(new Date());
        } else {
            // 更新物料
            enterpriseMaterial.setUpdaterCardId(dto.getCardId());
            enterpriseMaterial.setBaseUpdateTime(new Date());
        }
        this.saveOrUpdate(enterpriseMaterial);
        return Message.success();
    }

    @Override
    public List<CardEnterpriseMaterial> getEnterpriseMaterialPage(CardEnterpriseMaterialDto dto, Page<CardEnterpriseMaterial> page) {
        return cardEnterpriseMaterialMapper.selectEnterpriseMaterialPage(dto, page);
    }
}
